package com.example.wangzh.mytest.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.widget.ScrollView;

import com.example.wangzh.mytest.R;
import com.example.wangzh.mytest.constant.LogTag;
import com.example.wangzh.mytest.databinding.CustomAttrTestBinding;
import com.example.wangzh.mytest.utils.LogUtils;

import org.xmlpull.v1.XmlPullParser;

/**
 * Created by wangzh on 2017/10/26.
 */

public class AttrTestView extends ScrollView {
    public static final int a = 0x00000000;
    public static final int b = 0x00000001;
    public static final int[] ENUMS = {a, b};
    public static final int A = 0x00000001;
    public static final int B = 0x00000010;
    public static final int C = 0x00000100;
    public static final int D = 0x00001000;
    public static final int E = 0x00010000;
    public static final int F = 0x00100000;
    public static final int G = 0x01000000;
    public static final int H = 0x10000000;
    public static final int[] FLAGS = {A, B, C, D, E, F, G, H};

    Context mContext;
    boolean bool;
    int integer;
    float aFloat;
    float fraction;
    String str;
    int color;
    ColorStateList colorB;
    ColorStateList colorC;
    int pixSize;
    int mEnum;
    int mFlag = 0x00000000;
    CustomAttrTestBinding binding;

    public AttrTestView(Context context) {
        this(context, null);
    }

    public AttrTestView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AttrTestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        LayoutInflater.from(context).inflate(R.layout.custom_attr_test, this);
        binding = CustomAttrTestBinding.bind(this);
        loadAttr(attrs, defStyleAttr);
    }

    private void loadAttr(AttributeSet attrs, int defStyleAttr) {
        Resources.Theme theme = mContext.getTheme();
        TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.AttrTestView, defStyleAttr, 0);
        //如果使用某控件的时候没写某个属性，那么TypedArray里面就没有对应的一项
        //所以这里可以过滤一下，防止获取本来没有的属性
        int n = a.getIndexCount();
        for (int i = 0; i <= n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.AttrTestView_AttrTestView_boolean:
                    bool = a.getBoolean(attr, false);
                    binding.txtBoolean.setText("" + bool);
                    break;
                case R.styleable.AttrTestView_AttrTestView_integer:
                    integer = a.getInteger(attr, 0);
                    integer = a.getInt(attr, 0);
                    //两个方法有细微区别
                    binding.txtInteger.setText("" + integer);
                    break;
                case R.styleable.AttrTestView_AttrTestView_float:
                    aFloat = a.getFloat(attr, 0);
                    binding.txtFloat.setText("" + aFloat);
                    break;
                case R.styleable.AttrTestView_AttrTestView_fraction:
                    fraction = a.getFraction(attr, 1, 1, 0);
                    binding.txtFraction.setText("" + fraction);
                    break;
                case R.styleable.AttrTestView_AttrTestView_string:
                    str = a.getString(attr);
                    str = a.getText(attr).toString();
                    binding.txtString.setText(str);
                    //str=a.getNonResourceString(attr);//只能获取非资源String，没有用过
                    break;
                case R.styleable.AttrTestView_AttrTestView_color:
                    color = a.getColor(attr, 0);
                    binding.txtColor.setTextColor(color);
                    break;
                case R.styleable.AttrTestView_AttrTestView_color_b:
                    colorB = a.getColorStateList(attr);//这里xml文件中必须是颜色或者selector否则报错
//              <?xml version="1.0" encoding="utf-8"?>
//              <selector xmlns:android="http://schemas.android.com/apk/res/android">
//                  <item android:state_pressed="true">
//                      <shape android:shape="rectangle">
//                          <solid android:color="@color/red"></solid>
//                       </shape>
//                  </item>
//                  <item android:color="#ff0000ff" android:state_focused="true" />
//                     <item android:color="#ff000000" />
//              </selector>
                    binding.txtColor2.setTextColor(colorB);
                    break;
                case R.styleable.AttrTestView_AttrTestView_color_c:
//                    这种方法只适用于@drawable，格式只能是selector,而且颜色可能失真，不建议使用，了解一下xml解析即可
                    int textColorResId = a.getResourceId(attr, 0);
                    XmlPullParser xrp;
                    if (textColorResId == 0) {
                        LogUtils.i(LogTag.ERROR, getClass().getSimpleName() + ":加载参数出错");
                        return;
                    } else {
                        xrp = getResources().getXml(textColorResId);
                    }
                    try {
                        colorC = ColorStateList.createFromXml(getResources(), xrp);
                    } catch (Exception e) {
                    }
                    binding.txtColor3.setTextColor(colorC);
                    break;
                case R.styleable.AttrTestView_AttrTestView_dimension:
//                    这三个方法获取到的都是像素
                    pixSize = a.getDimensionPixelSize(attr, 0);
                    int pixelOffset = a.getDimensionPixelOffset(attr, 0);
                    float dimension = a.getDimension(attr, 0);
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append("DimensionPixelSize:");
                    stringBuffer.append(pixSize + "\n");
                    stringBuffer.append("DimensionPixelOffset:");
                    stringBuffer.append(pixelOffset + "\n");
                    stringBuffer.append("Dimension:");
                    stringBuffer.append(dimension);
                    binding.txtDimension.setText(stringBuffer.toString());
                    //给TextView设置字体大小的时候要注意单位
                    binding.txtDimension.setTextSize(TypedValue.COMPLEX_UNIT_PX, pixSize);
//                    以下两个是getDimensionPixelSize的特殊版本，不推荐使用
//                    color=a.getLayoutDimension(attr,0);
//                    color=a.getLayoutDimension(attr,"");
                    break;
                case R.styleable.AttrTestView_AttrTestView_reference_drawable:
                    Drawable drawable = a.getDrawable(attr);
                    binding.txtReferenceDrawable.setBackgroundDrawable(drawable);
                    break;
                case R.styleable.AttrTestView_AttrTestView_reference_array:
                    //第一种获取方法
                    CharSequence[] charSequences = a.getTextArray(attr);
                    binding.txtReferenceArray.setText(getCombinedString(charSequences));
                    //第二种获取方法
                    int strsResId = a.getResourceId(attr, 0);
                    if (strsResId == 0) {
                        LogUtils.i(LogTag.ERROR, getClass().getSimpleName() + ":加载参数出错");
                        return;
                    }
                    String[] strs = getResources().getStringArray(strsResId);
                    binding.txtReferenceArrayB.setText(getCombinedString(strs));
                    break;
                case R.styleable.AttrTestView_AttrTestView_enum:
                    int index = a.getInt(attr, 0);
                    mEnum = ENUMS[index];
                    binding.txtEnum.setText(mEnum + "");
                    break;
                case R.styleable.AttrTestView_AttrTestView_flag:
                    mFlag = a.getInt(attr, 0);
                    showContainFlags();
                    break;
                default:
                    break;
            }
        }
        //直接获取系统属性，不建议使用
        int resourceId = attrs.getAttributeResourceValue(
                "http://schemas.android.com/apk/res/android", "color", 0);
        ColorStateList csl = getResources().getColorStateList(resourceId);
        binding.txtAndroidColor.setTextColor(csl);
    }

    private void showContainFlags() {
        StringBuffer sb = new StringBuffer();
        if (containFlag(A)) {
            sb.append("A ");
        }
        if (containFlag(B)) {
            sb.append("B ");
        }
        if (containFlag(C)) {
            sb.append("C ");
        }
        if (containFlag(D)) {
            sb.append("D ");
        }
        if (containFlag(E)) {
            sb.append("E ");
        }
        if (containFlag(F)) {
            sb.append("F ");
        }
        if (containFlag(G)) {
            sb.append("G ");
        }
        if (containFlag(H)) {
            sb.append("H ");
        }
        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        binding.txtFlag.setText(sb.toString());
    }

    private boolean containFlag(int flag) {
        return (mFlag & flag) != 0;
    }

    private void clearFlag(int flag) {
        mFlag &= ~flag;
    }

    /**
     * @param flag 只能用FLAGS里面的int
     */
    public void setFlag(int flag) {
        mFlag |= flag;
    }

    private String getCombinedString(CharSequence[] charSequences) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < charSequences.length; i++) {
            stringBuffer.append(charSequences[i]);
            stringBuffer.append(" ");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        return stringBuffer.toString();
    }
}
